package com.zjw.yyyy2021.mmdd0927;

import java.util.HashMap;

/**
 * <p>TODO</p>
 *
 * @author 郑大仙丶
 * @version V1.0.0
 * @date 2021/9/27 23:24
 */
public class MMdd0927 {

    /**
     * 暴力枚举法
     * @param nums
     * @param k
     * @return
     */
    public int subarraySum1(int[] nums, int k) {
        int count = 0;
        for (int i = 0; i < nums.length; i++) {
            int sum = 0;
            for (int j = i; j < nums.length; j++) {
                sum += nums[j];
                if(sum == k){
                    count++;
                }
            }
        }
        return count;
    }


    public int subarraySum2(int[] nums, int k) {
        int count = 0;
        HashMap<Integer,Integer> map = new HashMap();
        map.put(0,1);
        int sum = 0;
        for (int num : nums) {
            sum += num;
            count += map.getOrDefault(sum - k, 0);
            map.put(sum,map.getOrDefault(sum,0) + 1);
        }
        return count;
    }




}
